//
//  PhoteBrowerViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/6/27.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit
private let PhoteBrowerReuseIdentifier = "PhoteBrowerReuseIdentifier"
class PhoteBrowerViewController: UIViewController {
    /*
     1.首先我要知道,我点的是哪一张图片
     2.其次如果有多张图片我们还可以左右滑 ,要拿到多有图片的URL数组
     
     //1.可以初始化控件器的时候来传递参数,重写初始化方法
     //2.可以定义属性通过属性传值
     */
    
    /// 保存当前选择图片的index
    var currentIndex: Int?
    
    ///保存当前微博的所有图片
    var pictureURLS: [URL]?
    
    init(index: Int, picURLS: [URL]) {
        //swift中重写控制器的init方法 初始化本控制器  在调用父类控制器的方法
        currentIndex = index
        pictureURLS = picURLS
        
        super.init(nibName: nil, bundle: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //初始化UI
        setupUI()
    }
    
    /// 初始化UI
    func setupUI() -> Void {
        view.backgroundColor = UIColor.black
        
        //1.添加子控件
        view.addSubview(showPhotoColllcetion)
        view.addSubview(colseBtn)
        view.addSubview(conserveBtn)
        
        //2.布局子控件
        view.addConstraint(NSLayoutConstraint.init(item: colseBtn, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10))
        view.addConstraint(NSLayoutConstraint.init(item: colseBtn, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10))
        colseBtn.addConstraint(NSLayoutConstraint.init(item: colseBtn, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 100))
        colseBtn.addConstraint(NSLayoutConstraint.init(item: colseBtn, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 35))
        
        view.addConstraint(NSLayoutConstraint.init(item: conserveBtn, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10))
        view.addConstraint(NSLayoutConstraint.init(item: conserveBtn, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -10))
        conserveBtn.addConstraint(NSLayoutConstraint.init(item: conserveBtn, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 100))
        conserveBtn.addConstraint(NSLayoutConstraint.init(item: conserveBtn, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 35))
        
        showPhotoColllcetion.frame = CGRect(x: 0, y: 0, width: WIDTH, height: UIScreen.main.bounds.height)
        
        //3.设置collectionView属性
        showPhotoColllcetion.delegate = self
        showPhotoColllcetion.dataSource = self
        showPhotoColllcetion.register(PhotoBrowerCollectionViewCell.self, forCellWithReuseIdentifier: PhoteBrowerReuseIdentifier)
    }
    
    /// 关闭按钮点击事件
    func colseBtnClick() -> Void {
        print(#function)
        dismiss(animated: true, completion: nil)
    }
    
    /// 保存按钮的点击事件
    func conserveBtnClick() -> Void {
        print(#function)
        //1.拿到当前正在显示的cell (两种方法获取当前正在显示的cell)
//        let index = showPhotoColllcetion.indexPathsForVisibleItems.last
//        let cell = showPhotoColllcetion.cellForItem(at: index!) as! PhotoBrowerCollectionViewCell
        let cell  = showPhotoColllcetion.visibleCells.last as! PhotoBrowerCollectionViewCell
        
        //2.保存图片
        let image = cell.photoImage.image
        UIImageWriteToSavedPhotosAlbum(image!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    //oc中的方法转swift方法
    //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
    /// 保存图片的回调方法
    ///
    /// - Parameters:
    ///   - image: <#image description#>
    ///   - error: <#error description#>
    ///   - contextInfo: <#contextInfo description#>
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) -> Void {
        
        if error == nil {
            SVProgressHUD.showSuccess(withStatus: "保存成功")
        }else {
            SVProgressHUD.showError(withStatus: "保存失败")
        }
    }

    //MARK: -- 懒加载
    
    /// 关闭按钮
    private lazy var colseBtn: UIButton = {
        let btn = UIButton()
        btn.translatesAutoresizingMaskIntoConstraints = false
        btn.setTitle("关闭", for: UIControlState.normal)
        btn.setTitleColor(UIColor.white, for: UIControlState.normal)
        btn.backgroundColor = UIColor.gray
        btn.addTarget(self, action: #selector(colseBtnClick), for: UIControlEvents.touchUpInside)
        
        return btn
    }()
    
    /// 保存按钮
    private lazy var conserveBtn: UIButton = {
        let btn = UIButton()
        btn.translatesAutoresizingMaskIntoConstraints = false
        btn.setTitle("保存", for: UIControlState.normal)
        btn.setTitleColor(UIColor.white, for: UIControlState.normal)
        btn.backgroundColor = UIColor.gray
        btn.addTarget(self, action: #selector(conserveBtnClick), for: UIControlEvents.touchUpInside)
        
        return btn
    }()
    
    /// 加载collectionView
    private lazy var showPhotoColllcetion: UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhoteBrowerLayout())
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension PhoteBrowerViewController: UICollectionViewDelegate, UICollectionViewDataSource,PhotoBrowerCollectionViewCellDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLS!.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhoteBrowerReuseIdentifier, for: indexPath) as! PhotoBrowerCollectionViewCell
        cell.photoBrowerDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        cell.photoImageURL = pictureURLS?[indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
    }
    
    func photoBrowerCollectionViewCellDidClose(cell: PhotoBrowerCollectionViewCell) {
        dismiss(animated: true, completion: nil)
    }
}


//MARK: -- 创建布局

private class PhoteBrowerLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        itemSize = UIScreen.main.bounds.size//设置item的大小
        scrollDirection = UICollectionViewScrollDirection.horizontal//设置水平方像滚动
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
}




